package cc.catface.api.business.app;

import cc.catface.common.fastdfs.UploadMediaUtil;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@RestController
@RequestMapping("resource")
@Api(tags = "[文件]综合")
public class FastdfsController {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;


    @ApiOperation("上传")
    @PostMapping("upload")
    public String upload(MultipartFile file) throws IOException {
        System.out.println("upload, file:" + file);
        return UploadMediaUtil.upload(file, fastFileStorageClient);
    }

    @SneakyThrows
    @ApiOperation("下载")
    @GetMapping("download")
    public byte[] download(String fileId) {
        int index = fileId.indexOf("/");
        String s1 = fileId.substring(0, index);
        String s2 = fileId.substring(index + 1);
        byte[] bs = fastFileStorageClient.downloadFile(s1, s2, new DownloadByteArray());
        //writeBytes2Local(bs);
        return bs;
    }

    //将byte[]文件
    @SneakyThrows
    private void writeBytes2Local(byte[] bytes) {
        OutputStream out = new FileOutputStream("D:\\adding\\" + System.currentTimeMillis() + ".jpg");
        InputStream is = new ByteArrayInputStream(bytes);
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = is.read(buff)) != -1) {
            out.write(buff, 0, len);
        }
        is.close();
    }
}
